package com.huiyin.ui.videoplayer.player;

import java.io.IOException;

import com.huiyin.AppContext;
import com.huiyin.R;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceView;
import android.view.View;

public class PlayerManager implements OnPreparedListener {
	
	private static final String TAG = "PlayerManager";
	
	private static PlayerManager mPlayerManager;
	
	private MediaPlayer mMediaPlayer;
	
	private View mView;
	
	private PlayerManager() {
		mMediaPlayer = new MediaPlayer();
	}
	
	public static PlayerManager getInstance() {
		if(mPlayerManager == null) {
			mPlayerManager = new PlayerManager();
		}
		return mPlayerManager;
	}
	
	public View getView() {
		return mView;
	}
	
	public void initMediaPlayer(SurfaceView mSurfaceView, String src) {
		Log.d(TAG, "initMediaPlayer : src = " + src);
		try {
			mMediaPlayer.reset();  
			mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);  
			mMediaPlayer.setDataSource(src);
	         //把视频画面输出到SurfaceView  
			mMediaPlayer.setDisplay(mSurfaceView.getHolder());  
			mMediaPlayer.prepareAsync();  
			mMediaPlayer.setOnPreparedListener(this);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}  
	}
	
	public boolean isPlaying() {
		Log.d(TAG, "playerManager : isPlaying = " + mMediaPlayer.isPlaying());
		return mMediaPlayer.isPlaying();
	}
	
	public void start() {
		Log.d(TAG, "playerManager : start");
		mMediaPlayer.start();
	}
	
	public void pause() {
		Log.d(TAG, "playerManager : pause");
		mMediaPlayer.pause();
	}
	
	public void stop() {
		Log.d(TAG, "playerManager : stop");
		mMediaPlayer.stop();
	}
	
	public void seekTo(int msec) {
		Log.d(TAG, "playerManager : seekTo = " + msec);
		mMediaPlayer.seekTo(msec);
	}

	@Override
	public void onPrepared(MediaPlayer mp) {
		Log.d(TAG, "playerManager : duration = " + mMediaPlayer.getDuration());
		mMediaPlayer.seekTo(mMediaPlayer.getDuration()/3);
	}

}
